package com.bwie.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.nacos.api.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.utils.R;
import com.bwie.utils.TokenUtil;
import com.bwie.vo.PageInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.BrandMapper;
import com.bwie.pojo.Brand;
import com.bwie.service.BrandService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: 鑫仔
 * @Date: 2025/7/19 10:02
 * @Description:
 **/
@Transactional
@Service
@Slf4j
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private HttpServletRequest request;

    @Override
    public R brandList(PageInfoVo pageInfoVo) {
        Page<Brand> brandPage = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        LambdaQueryWrapper<Brand> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Brand::getCreateTime);
        if (ObjectUtils.isNotEmpty(pageInfoVo.getKeyWord())) {
            wrapper.like(Brand::getBrandName, pageInfoVo.getKeyWord());
        }
        Page<Brand> page = brandMapper.selectPage(brandPage, wrapper);
        return R.OK(page);
    }

    @Override
    public R addBrand(Brand brand) {
        String token = request.getHeader("token");
        String userName = TokenUtil.getUserName(token);
        Brand brandDb = brandMapper.selectOne(new LambdaQueryWrapper<Brand>().eq(Brand::getBrandName, brand.getBrandName()));
        if (ObjectUtil.isNotEmpty(brandDb)) {
            log.info("不可重复添加品牌");
            return R.ERROR(500, "不可重复添加品牌");
        }

        brand.setCreateBy(userName);
        brand.setCreateTime(new Date());

          brandMapper.insert(brand);


        log.info("添加品牌成功");
        return R.OK();
    }

    @Override
    public R updateStatus(Brand brand) {
        brand.setBrandStatus(
                brand.getBrandStatus()
        );
        brandMapper.updateById(brand);
        return R.OK();
    }

    @Override
    public R deleteBatchBrand(List<Integer> ids) {
        brandMapper.deleteBatchIds(ids);
        return R.OK();
    }
}
